/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.lt.cj.config.util;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.lt.cj.config.entities.ConfigModel;
import org.lt.cj.core.Seed;

/*
 * @author luohong
 */
public class RegCheck {

    private Pattern pattern;
    private static RegCheck regChecker = new RegCheck();

    private RegCheck() {
    }

    public static RegCheck getInstance() {

        if (regChecker == null) {
            regChecker = new RegCheck();
        }
        return regChecker;
    }

    /* 检查url是否符合匹配要求 */
    public boolean checkUrl(String url, List<String> regList) {

        if (url.trim().equals("")) {
            return false;
        }
        for (int i = 0; i < regList.size(); i++) {
            pattern = Pattern.compile(regList.get(i));
            Matcher matcher = pattern.matcher(url);
            boolean result = matcher.matches();
            if (result) {
                return true;
            }
        }
        return false;
    }

    /* 检查节点的内容匹配 */
    public boolean checkNodeContent(String content, String reg) {

        pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(content);
        boolean result = matcher.matches();
        if (result) {
            return true;
        }
        return false;
    }

    /* 检查节点的内容匹配 */
    public boolean checkCategory(Seed parent, Seed child, ConfigModel configModel) {

        //验证子种子中是不是存在分类地址
        //如果parent的URL符合父种子的URL匹配规则
        String reg = configModel.getFitUrlRegs().get(1);
        pattern = Pattern.compile(reg);
        Matcher matcher = pattern.matcher(parent.getUrl());
        boolean parentResult = matcher.matches();

        //如果child的URL符合子种子的URL匹配规则
        reg = configModel.getFitUrlRegs().get(2);
        pattern = Pattern.compile(reg);
        matcher = pattern.matcher(child.getUrl());
        boolean childResult = matcher.matches();

        //当以上匹配结果都为true时，才可说明两个种子是父种子和子种子
        if (parentResult && childResult) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        RegCheck regChecker = RegCheck.getInstance();
        String url = "http://list.tmall.com/50023887/g-st-----40-0--50023887-x.htm?TBG=55137.91908.7";
        url = "http://www.tmall.com/go/act/tmall/iwanttobuy.php?TBG=55137.91908.2&initShow=1";
        url = "http://item.tmall.com/item.htm?id=9284868304&prc=1&is_b=1";
        List<String> list = new ArrayList<String>();
        list.add("http://list\\.tmall\\.com/.*");
        list.add("http://www\\.tmall\\.com/go/act/tmall/iwanttobuy\\.php.*");
        list.add("http://item\\.tmall\\.com/item\\.htm.*");
        regChecker.checkUrl(url, list);

    }
}
